#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <set>

using namespace std;

class Solution {
    public:
        int searchInsert(int A[], int n, int target) {
            int lo = 0, hi = n-1;
            while (lo < hi) {
                int mid = lo + (hi-lo)/2;
                if (A[mid] == target) return mid;
                if (A[mid] < target) lo = mid+1;
                else hi= mid-1; 
            }
            //cout << lo << " " << hi << endl;
            if (A[lo] < target) return lo+1;
            else if (A[lo] == target) return lo;
            else if (A[lo] > target && lo != 0) return lo;
            else if (A[lo] > target && lo == 0) return 0;
                               
        }
};

//add much better code


//nt searchInsert(int A[], int n, int target) {
        int lo = 0, hi = n-1;
        if (target < A[0]) return 0;
        if (target > A[n-1]) return n;
        while(lo <= hi) {
           int mid = lo + (hi-lo)/2;
            if (A[mid] == target) return mid;
            else if (A[mid] < target) lo = mid+1;
            else hi = mid-1;
        }
        if (A[lo] > target) return lo;
        else if (A[lo] < target) return  lo+1;

    }
//ttest in 1337 online judge and pass all the test
int main(int argc, char **argv)
{
    Solution mySolution;
    int pos;

    cout << "-----------------Test 1--------------------" << endl;
    int input[] = {1,3};
    pos = mySolution.searchInsert(input, sizeof(input)/sizeof(int), 2);
    cout << pos << endl;
    

    cout << "-----------------Test 2--------------------" << endl;
    pos = mySolution.searchInsert(input, sizeof(input)/sizeof(int), 2);
    cout << pos << endl;


    cout << "-----------------Test 3--------------------" << endl;
    pos = mySolution.searchInsert(input, sizeof(input)/sizeof(int), 7);
    cout << pos << endl;


    cout << "-----------------Test 4--------------------" << endl;
    pos = mySolution.searchInsert(input, sizeof(input)/sizeof(int), 0);
    cout << pos << endl;


    cout << "-----------------Test 5--------------------" << endl;
    int test[] = {1,3,5};
    pos = mySolution.searchInsert(test, sizeof(test)/sizeof(int), 5);
    cout << pos << endl;


}
